package com.wpw.dream.masteworker;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Master {

	//任务队列
	ConcurrentLinkedQueue<Task> taskQueue = new ConcurrentLinkedQueue<>();

	//装载所有的worker
	Map<Object, Thread> workersMap = new HashMap<>();
	
	//装载worker的处理结果
	ConcurrentHashMap<Object, Object> resMap = new ConcurrentHashMap<>();
	

	public void addWorker(Worker worker) {
		//worker需要从任务队列中获取任务
		worker.setTaskQueue(taskQueue);
		//worker需将任务处理结果放入resMap
		worker.setResMap(resMap);
		//暂且用hashcode,不同的对象hash可能相同
		workersMap.put(worker.hashCode(), worker);
	}
	
	//添加任务
	public void addTask(Task task) {
		taskQueue.add(task);
	}
	
	//执行worker，处理任务
	public void excute() {
		for (Map.Entry<Object, Thread> me : workersMap.entrySet()) {
			me.getValue().start();
		}
	}
	
	//判断是否所有的worker执行完毕
	private Boolean isComplete() {
		for (Map.Entry<Object, Thread> me : workersMap.entrySet()) {
			if(me.getValue().getState()!=Thread.State.TERMINATED){  
                return false;  
            }  
		}
		return true;
	}
	
	public Map<Object, Object> getResult() {
		while (true) {
			if (isComplete()) {
				return resMap;
			}
		}
	}
	
}
